<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      .error {
        color: red;
        font-size: 14px;
      }
    </style>
  </head>
  <body>
    <form action="abc" name="myForm">
      <input type="text" name="username" /><label class="error"></label>
      <br />
      <input type="password" name="password" />
      <input type="submit" value="提交" />
    </form>
    <script src="02.js"></script>
    <script>
      // myForm  document.myForm  document.forms[0]  document.querySelector();
      // 表单提交事件
      myForm.onsubmit = function (e) {
        // 阻止默认行为
        // e.preventDefault();
        // 获取表单数据
        console.log(this.username.value, this.password.value);
        // TODO 验证表单数据
        let username = this.username.value;
        // 通过正则校验用户名是否合法：字母开头，字母数字下划线组成，长度6-12位
        let reg = /^[a-zA-Z]\w{5,11}$/;
        if (!reg.test(username)) {
          this.username.focus();
          // 输入框后显示提示信息
          this.username.nextElementSibling.innerHTML = "用户名不合法";
          // 设置输入框边框颜色为红色
          this.username.style.outlineColor = "red";
          // 设置输入框获取焦点时边框颜色为蓝色
          return false;
        }

        // TODO 发送ajax请求/ return true;
        return false; // 阻止表单提交
      };
    </script>
  </body>
</html>
